#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "protocol.hpp" // 形成约定
#include <unistd.h>
#include <cstring>
#include "InetAddr.hpp"
#include "Log.hpp"
#include "Common.hpp"

using namespace LogModule;

int main(int argc, char* argv[])
{


    // 。/client_tcp server_ip server_port
    if (argc != 3)
    {
        std::cout << "Usage:./client_tcp server_ip server_port" << std::endl;
        return 1;

    }
    std::string server_ip = argv[1];
    int server_port = std::stoi(argv[2]);

    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::FATAL) << "socket create fail!" ;
        Die(SOCKET_ERR);
    }

    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = ::htons(server_port);
    server_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());
    // zdl:: client 不需要显示的绑定 tcp是面向连接的, connect 就会自动的进行bind
    int n = ::connect(sockfd, CONV(&server_addr), sizeof(server_addr));
    if (n < 0)
    {
        LOG(LogLevel::FATAL) << "connect error";
        Die(CONNECT_ERR);
    }
    // echo srever
    std::string message;
    while (true)
    {
        
        double x, y; char oper;
        std::cout << "input x:";
        std::cin >> x;
        std::cout << "input oper:";
        std::cin >> oper;
        std::cout << "input y:";
        std::cin >> y;
        
        Request req(x, y, oper);
        // 1. 序列化
        req.Serialize(message);
        // 2. encode
        Encode(message);
        // 3. send
        int n = ::send(sockfd, message.c_str(), message.size(), 0);
        // 4. 获得应答
        if (n > 0)
        {
            char inbuffer[1024];
            int m = ::recv(sockfd, inbuffer, sizeof(inbuffer), 0);
            if ((m > 0))
            {
                inbuffer[m] = 0;
                std::string package = inbuffer;
                std::string content;
                // 4. 保证应答的完整性
                Decode(package, &content);
                // 5. 反序列化
                Response resp;
                resp.Deserialize(content);

                // 6. 得到结构化的数据
                std::cout << (double)resp.Ret() << " code[ " << resp.Code() << " ]" << std::endl;
            }
            else 
            {
                break;
            }
        }
    }
    ::close(sockfd);

    return 0;
}